/**
 * 
 */
package com.qq.spirit;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlAnchor;
import com.gargoylesoftware.htmlunit.html.HtmlForm;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.html.HtmlPasswordInput;
import com.gargoylesoftware.htmlunit.html.HtmlSubmitInput;
import com.gargoylesoftware.htmlunit.html.HtmlTextInput;
import com.gargoylesoftware.htmlunit.util.Cookie;
import com.gargoylesoftware.htmlunit.util.NameValuePair;
import com.qq.spirit.image.ImageCodeUtil;
import com.qq.spirit.inter.AbstractActionAfterHttpRequest;
import com.qq.spirit.inter.IActionAfterHttpRequest;
import com.qq.spirit.inter.TaskUnit;
import com.qq.spirit.model.UserData;
import com.qq.spirit.model.XmlNodeData;

/**
 * @author beedoorwei
 * 
 */
public class LoginTask extends TaskUnit
{
	public LoginTask()
	{
		this.username = "登录任务";
	}

	private TaskUnit a;

	public LoginTask(String username, TaskUnit a)
	{
		super();
		this.username = username;
		this.a = a;
	}

	public void doTask()
	{
		synchronized (LoginTask.class)
		{
			Map<String, String> uSessionmap = new HashMap<String, String>();
			uSessionmap.put("mushuai0815", "JSESSIONID=D91903C2EDE840F28FCD03D42489CA42");
			uSessionmap.put("geshengsen7971", "JSESSIONID=3911F489CDB51CC2DE2378F2A5F66C11");
			uSessionmap.put("chenjiewda1", "JSESSIONID=F5577A945C75F1F4EEED30B010983FE5");
			uSessionmap.put("cyb120", "JSESSIONID=42F62D2F757CE80A1771F787996E803A");
			uSessionmap.put("xmg1974", "JSESSIONID=659010276F143C97442493CB762CD739");
			UserData u = UserCache.get(username);
			u.setUserState(UserState.LOGIN_GAME);
			u.getClient().addRequestHeader("Cookie", uSessionmap.get(username));

			// 需要触发一次获取个人信息的调用
			HttpUtil.doGet(username, GameConstants.PLAY_USER_INFO_URL, new SessionHolderResult(username));
			// if (u.getUserState() == UserState.INIT)
			// {
			// LoggerUtil.info(username + "\t当前状态\t" + u.getUserState());
			// // 初始状态，需要登录咯，登录完毕，将状态设置为LOGIN_WEB状态
			// loginWeb(u, username);
			// }
			//
			// // 已经登录了网站，需要构建JSESSIONID
			// if (u.getUserState() == UserState.LOGIN_WEB)
			// {
			// // 生成JSESSIONID
			// loginGame(u);
			// }
			if (a != null)
			{
				TaskManager.addTask(a);
			}
		}
	}

	/**
	 * 登录游戏
	 * 
	 * @param u
	 */
	private void loginGame(UserData u)
	{
		try
		{
			// 操作步骤为先刷新要玩首页
			HtmlPage page = u.getClient().getPage("http://www.yaowan.com");
			System.out.println(page.asText());
			HtmlAnchor ha = page.getAnchorByText("双线百零三区");
			if (ha != null)
			{
				// 登录成功
				ha.click();
				if (isGameJSessionId(u.getUsername()))
				{
					u.setUserState(UserState.LOGIN_GAME);
					HttpUtil.doGet(u.getUsername(), GameConstants.PLAY_USER_INFO_URL, new SessionHolderResult(u.getUsername()));
				}
			}
		} catch (IOException e)
		{
			LoggerUtil.error(e);
		}
	}

	/**
	 * 登录WEB
	 * 
	 * @param u
	 */
	private void loginWeb(UserData u, String username1)
	{
		try
		{
			HtmlPage page = u.getClient().getPage("http://www.yaowan.com/?m=user&action=login");
			List<HtmlForm> hfList = page.getForms();
			if (!hfList.isEmpty())
			{
				HtmlForm hf = hfList.get(0);
				HtmlSubmitInput button = hf.getInputByName("button");
				HtmlPasswordInput password = hf.getInputByName("password");
				HtmlTextInput username = hf.getInputByName("username");
				HtmlTextInput codeinput = null;
				if (hf.hasHtmlElementWithId("code"))
				{
					codeinput = hf.getInputByName("code");
				}

				username.setValueAttribute(u.getUsername());
				password.setValueAttribute(u.getPassword());
				if (codeinput != null)
				{
					String code = ImageCodeUtil.getImageCode(u.getUsername());
					codeinput.setValueAttribute(code);
				}
				final HtmlPage page2 = button.click();

				HtmlAnchor ha = page2.getAnchorByText("充值明细");
				if (ha != null)
				{
					// 登录成功
					u.setUserState(UserState.LOGIN_WEB);

					HtmlAnchor hagame = page2.getAnchorByText("双线百零三区");
					if (hagame != null)
					{
						hagame.click();

						if (isGameJSessionId(u.getUsername()))
						{
							u.setUserState(UserState.LOGIN_GAME);
							HttpUtil.doGet(username1, GameConstants.PLAY_USER_INFO_URL, new SessionHolderResult(username1));
						}
					}
				}
			}
		} catch (IOException e)
		{
			LoggerUtil.error(e);
		}
	}

	/**
	 * @param username
	 * @return
	 */
	private static boolean isGameJSessionId(String username)
	{
		UserData u = UserCache.get(username);
		Set<Cookie> cookieSet = u.getClient().getCookieManager().getCookies();
		Iterator<Cookie> ite = cookieSet.iterator();
		while (ite.hasNext())
		{
			Cookie c = ite.next();
			if (c.getName().equals("JSESSIONID") && c.getDomain().indexOf("s103.as.yaowan.com") >= 0)
			{
				System.out.println(c.getValue());
				return true;
			}
		}

		return false;
	}

	/**
	 * 网站登录功能处理
	 * 
	 * @author Administrator
	 * 
	 */
	class AfterLoginWebAction extends AbstractActionAfterHttpRequest
	{

		public AfterLoginWebAction(String username)
		{
			super();
			this.username = username;
		}

		@Override
		public void doCall(List<NameValuePair> headerList, XmlNodeData content)
		{
			// 如果有Set-Cookie：userid 字段，则认为是登录成功了，否则是登录失败，继续登录
			for (NameValuePair h : headerList)
			{
				if (h.getName().equalsIgnoreCase("Set-Cookie"))
				{
					String v = h.getValue();
					if (v.indexOf("userid") != -1)
					{
						LoggerUtil.info(username + " loginWeb suc ");
						UserCache.get(username).setUserState(UserState.LOGIN_WEB);
						break;
					}
				}
			}
		}
	}

}
